package com.dobbyspringside.modules.persistence;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * Created by liguoqing on 2016/2/16.
 */
public class SearchFilter {

    public enum Operator {
        EQ, LIKE, GT, LT, GTE, LTE
    }

    public String fieldName;
    public Object value;
    public Operator operator;

    public SearchFilter(String fieldName, Operator operator, Object value) {
        this.fieldName = fieldName;
        this.operator = operator;
        this.value = value;
    }

    /**
     * searchParams中key的格式为OPERATOR_FIELDNAME
     * @param searchParams
     * @return
     */
    public static Map<String, SearchFilter> parse(Map<String,Object> searchParams) {
        Map<String,SearchFilter> filters = Maps.newHashMap();

        for(Map.Entry<String,Object> entry : searchParams.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            // 过滤空值
            if(StringUtils.isBlank((String)value)) {
                continue;
            }
            String[] names = StringUtils.split(key,"_");
            if(names.length != 2) {
                throw new IllegalArgumentException(key + "is not a valid search filter name");
            }
            String fieldName = names[1];
            Operator operator = Operator.valueOf(names[0]);

            // 创建 SearchFilter
            SearchFilter searchFilter = new SearchFilter(fieldName,operator,value);
            filters.put(key,searchFilter);
        }

        return filters;
    }
}
